<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\user\client;
use think\facade\Db;
use app\wework\controller\Base;
use app\wework\model\user\client\CustomerModel;
use app\wework\model\QyWechatApi;
use app\wework\model\Helper;
use think\facade\Session;
use think\facade\Log;
include "../extend/PHPExcel/php-excel.class.php";

class Customer extends Base
{
    /**
     * 客户列表. 客户阶段暂无 客户管理标签暂无查询
     * @return
     */
    public function index(){
        $add_ways = addWay();
        $wid = Session::get('wid');
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
        $add_way = $this->req->param("add_way");
        $name = $this->req->param("name");
        $gender = $this->req->param("gender");
        $status = $this->req->param("status");
        $staff_id = $this->req->param("staff_id");
        $tags = $this->req->param("tags");
        $times = $this->req->param("times");
        $res = CustomerModel::info($page,$name,$staff_id,$tags,$times,$add_way,$gender,$status,$size,$add_ways);

        return success('客户列表',$res);
    }

    public function downexcel(){
        $add_ways = addWay();
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
        $wid = $this->req->param("wid");
        if(!$wid)return error("参数错误");
        $add_way = $this->req->param("add_way");
        $name = $this->req->param("name");
        $gender = $this->req->param("gender");
        $status = $this->req->param("status");
        $staff_id = $this->req->param("staff_id");
        if($staff_id)$staff_id = explode(",",$staff_id);
        $tags = $this->req->param("tags");
        if($tags)$tags = explode(",",$tags);
        $times = $this->req->param("times");
        if($times)$times = explode(",",$times);
        $res = CustomerModel::info($page,$name,$staff_id,$tags,$times,$add_way,$gender,$status,$size,$add_ways,$wid);
        $arr = [
            0 => ['客户名称', '性別','所属客户名称', '添加渠道', '客户评分', '客户积分', '客户标签', '添加渠道','客户状态','添加时间']
        ];
        $i = 1;
        foreach($res["item"] as $value){
            $arr[$i]["客户名称"] = $value["name"];
            if($value["gender"] == 0)$arr[$i]["性別"] = "未知";
            if($value["gender"] == 1)$arr[$i]["性別"] = "男性";
            if($value["gender"] == 2)$arr[$i]["性別"] = "女性";
            $arr[$i]["所属客户名称"] = $value["staff_name"];
            $arr[$i]["添加渠道"] = $value["add_way"];
            $arr[$i]["客户评分"] = $value["score"];
            $arr[$i]["客户积分"] = $value["integral"];
            $arr[$i]["客户标签"] = implode(",", array_column($value["tags"], "tag_name"));
            if($value["status"] == 0)$arr[$i]["客户状态"] = "正常";
            if($value["status"] == 1)$arr[$i]["客户状态"] = "已流失-员工删除客户";
            if($value["status"] == 1)$arr[$i]["客户状态"] = "已流失-客户删除员工";
            $arr[$i]["添加时间"] = $value["createtime"];
            $i++;
        }
        $str = "客户列表";
        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
    }

    //批量修改评分
    public function updScore(){
        $size = $this->req->param("size");
        $ids = $this->req->param("ids");
        $type = $this->req->param("type");
        if(!$ids || !$size || !$type)return error("必填项不可为空");
        $res = CustomerModel::updScore($ids,$size,$type);

        return success("操作成功");
    }
    //批量修改积分
    public function updIntegral(){
        $size = $this->req->param("size");
        $ids = $this->req->param("ids");
        $type = $this->req->param("type");
        if(!$ids || !$size || !$type)return error("必填项不可为空");
        $res = CustomerModel::updIntegral($ids,$size,$type);

        return success("操作成功");
    }


    /**
    * 客户列表
    * @param  只需要wid查到全部员工数据
    * @return 
    */
    public function sync(){
        $wid = Session::get('wid');
        $config = Db::table('kt_wework_config')->where('wid',$wid)->find();
        if(!$config["customer_secret"]){ return error("客户联系未配置，请先配置客户联系");}
        $where["wid"] = $wid;
        $where["status"] = 1;
        $where["is_del"] = 0;
        $staffs = Db::table('kt_wework_staff')->field("userid,id")->where($where)->select()->toArray();
        $mh = curl_multi_init();
        $conn = [];
        $res = [];
        $url = $this->req->domain()."/wework/user/client/customer";
        for ($i=0;$i<count($staffs);$i++) {
            $data = http_build_query(["userid"=>$staffs[$i]["userid"],"wid"=>$wid]);
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
            curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
            curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do { $n=curl_multi_exec($mh,$active); }
        while ($active);
        $result = true;
        for ($i=0;$i<count($staffs);$i++) {
            $res[$i]=curl_multi_getcontent($conn[$i]);
            curl_close($conn[$i]);
            if($res[$i] != 1){
                 $result = false;
            }
        }
        return success('同步成功');
    }

    //批量打标签
    public function addTags(){
        $wid = Session::get('wid');
        $ids = $this->req->param("ids");
        $tags = $this->req->param("tags");
        $customerlist = CustomerModel::customerLists($ids);
        foreach($customerlist as $customer){
            if($customer["status"] != 0)continue;
            $tagParam = [
                'userid' => Helper::getUser(["id"=>$customer["staff_id"]])["userid"],
                'external_userid' => $customer['external_userid'],
                'add_tag' => $tags,
                'remove_tag'=> [],
            ];
            $res = QyWechatApi::editMarkTag($tagParam,$wid);
            if($res["errcode"] != 0)return error("操作失败",$res["errcode"]);
            $customer_tag = $customer["tags"];
            $add_tag = array_unique(array_merge($customer_tag,$tags));
            Db::table('kt_wework_customer')->where('id',$customer['id'])->json(['tags',"tag_info"])->save(['tags'=>$add_tag,'tag_info'=>$add_tag]);
        }

        return success('操作成功');
    }

    //批量打标签
    public function delTags(){
        $wid = Session::get('wid');
        $ids = $this->req->param("ids");
        $tags = $this->req->param("tags");
        $customerlist = CustomerModel::customerLists($ids);
        $add_tag = [];
        foreach($customerlist as $customer){
            if($customer["status"] != 0)continue;
            $tagParam = [
                'userid' => Helper::getUser(["id"=>$customer["staff_id"]])["userid"],
                'external_userid' => $customer['external_userid'],
                'add_tag' => [],
                'remove_tag'=> $tags,
            ];
            $res = QyWechatApi::editMarkTag($tagParam,$wid);
            if($res["errcode"] != 0)return error("操作失败",$res["errcode"]);
            $customer_tag = $customer["tags"];
            foreach($customer_tag as $key=>$tag){
                if(!in_array($tag,$tags))$add_tag[] = $tag;
            }
            Db::table('kt_wework_customer')->where('id',$customer['id'])->json(['tags',"tag_info"])->save(['tags'=>$add_tag,'tag_info'=>$add_tag]);
        }

        return success('操作成功');
    }

    public function customer(){
        $datas = $_POST;
        $userid = $datas["userid"];
        $wid = $datas["wid"];
        $res = QyWechatApi::getCustomerList($wid,array($userid));

        $sql = "INSERT INTO kt_wework_customer ( wid, external_userid, name,avatar,type,gender,unionid,position,corp_name,corp_full_name,external_profile,staff_id,remark,description,createtime,tags_info,tags,remark_corp_name,remark_mobiles,add_way,oper_userid,state) VALUES";
        foreach($res as $customer_info){
            $staff = Helper::getUser(['wid'=>$wid,'userid'=>$customer_info['follow_info']["userid"]]);
            $user = $customer_info['follow_info'];
            $wid = $wid;
            $external_userid = $customer_info['external_contact']['external_userid'];
            $name = filterEmoji($customer_info['external_contact']['name']);
            $avatar = $customer_info['external_contact']['avatar'];
            $type = $customer_info['external_contact']['type'];
            $gender = $customer_info['external_contact']['gender'];
            $unionid = "";
            $position = "";
            $corp_name = "";
            $corp_full_name = "";
            $external_profile = "";
            if(array_key_exists("unionid",$customer_info['external_contact']))$unionid = $customer_info['external_contact']['unionid'];
            if(array_key_exists("position",$customer_info['external_contact']))$position = $customer_info['external_contact']['position'];
            if(array_key_exists("corp_name",$customer_info['external_contact']))$corp_name = $customer_info['external_contact']['corp_name'];
            if(array_key_exists("corp_full_name",$customer_info['external_contact']))$corp_full_name = $customer_info['external_contact']['corp_full_name'];
            if(array_key_exists("external_profile",$customer_info['external_contact']))$external_profile = json_encode($customer_info['external_contact']['external_profile']);
            $staff_id = $staff['id'];
            $remark = filterEmoji($user['remark']);
            $description = $user['description'];
            $createtime = $user['createtime'];
            $tags_info = json_encode($customer_info['follow_info']['tag_id'],320);
            $tags = json_encode($customer_info['follow_info']['tag_id'],320);
            $remark_corp_name = "";
            $remark_mobiles = "";
            $add_way = 0;
            $oper_userid = "";
            $state = "";
            if(array_key_exists("remark_corp_name",$user))$remark_corp_name = $user['remark_corp_name'];
            if(array_key_exists("remark_mobiles",$user))$remark_mobiles = json_encode($user['remark_mobiles'],320);
            if(array_key_exists("add_way",$user))$add_way = $user['add_way'];
            if(array_key_exists("oper_userid",$user))$oper_userid = $user['oper_userid'];
            if(array_key_exists("state",$user))$state = $user['state'];
            $data_list[] = "($wid,'{$external_userid}','{$name}','{$avatar}',{$type},{$gender},'{$unionid}','{$position}','{$corp_name}','{$corp_full_name}','{$external_profile}',{$staff_id},'{$remark}','{$description}','{$createtime}','{$tags_info}','{$tags}','{$remark_corp_name}','{$remark_mobiles}',{$add_way},'{$oper_userid}','{$state}')";
        }
        if(!count($data_list))return $res;
        $sql .= implode(',', $data_list);
        $sql .= "ON DUPLICATE KEY UPDATE name =  VALUES(name),avatar = VALUES(avatar),type =  VALUES(type),gender =  VALUES(gender),position =  VALUES(position),corp_name =  VALUES(corp_name),corp_full_name =  VALUES(corp_full_name),external_profile =  VALUES(external_profile),remark =  VALUES(remark),description =  VALUES(description),tags =  VALUES(tags),remark_corp_name =  VALUES(remark_corp_name),remark_mobiles =  VALUES(remark_mobiles),add_way =  VALUES(add_way),createtime =  VALUES(createtime),unionid =  VALUES(unionid)";
        $res = Db::execute($sql);

        return "1";
    }

    public function way(){
        $res = addWay();
        $datas = [];
        foreach($res as $key=>$value){
            $data["id"]= $key;
            $data["name"]= $value;
            $datas[] = $data;
        }
        
        return success('添加渠道',$datas);
    }

    /**
    *   @param id  客户信息id
    *   客户详情 入口 暂时缺少自定义信息
    */
    public function Info(){
        $addWay = addWay();
        $id = $this->req->param("id");
        $res = CustomerModel::customerInfo($id);
        $res["add_way"] = $addWay[$res["add_way"]];
        
        return success('客户详情',$res);
    }

    /**
    *  @param staff_id  员工id
    *  @param external_userid 客户external_userid
    *  客户详情，员工切换 客户信息汇总
    */
    public function customerInfo(){
        $addWay = addWay();
        $external_userid = $this->req->param("external_userid");
        $staff_id = $this->req->param("staff_id");
        if(!$external_userid) return error("参数错误");
        $customerlist = CustomerModel::customerAll($external_userid,$staff_id);
        $tagList = array_column($customerlist,"tags");
        foreach($tagList as $key=>$value){$tagList[$key] = json_decode($value,1);}
        $tags = array_reduce($tagList, function($tags,$value){
            return array_merge($tags,array_values($value));
        },array());
        if($tags){
            $tag_info = [];
            foreach(CustomerModel::tags(array_unique($tags)) as $value){
                $tag_info[$value["group_name"]]["name"] = $value["group_name"];
                if($tag_info[$value["group_name"]]["name"] == $value["group_name"]){
                    $tag_info[$value["group_name"]]["data"][] =  $value["tag_name"];
                }
            }
            $res["tag_info"] = array_values($tag_info);
        }
        foreach($customerlist as $key=>$customer){
            if($customer["add_way"])$customerlist[$key]["add_way"] = $addWay[$customer["add_way"]];
            $customerlist[$key]["createtime"] = date("Y-m-d H:i:s",$customer["createtime"]);
        }
        $res["customerlist"] = $customerlist;
        return success('客户详情',$res);
    }


    /**
    *  @param userid  员工id
    *  @param external_userid 客户external_userid
    *  客户详情，客户概况  最近沟通时间暂时不做  自定义信息暂时不做
    *  取消使用
    */
    // public function proifle(){
    //     $external_userid = $this->req->param("external_userid");
    //     $userid = $this->req->param("userid");
    //     $addWay = addWay();
    //     if($userid != "客户信息汇总") $customerlist = CustomerModel::customerAll($external_userid,$userid);
    //     if($userid == "客户信息汇总") $customerlist = CustomerModel::customerAll($external_userid);
    //     foreach($customerlist as $key=>$customer){
    //         $customerlist[$key]["add_way"] = $addWay[$customer["add_way"]];
    //         $customerlist[$key]["createtime"] = date("Y-m-d H:i:s",$customer["createtime"]);
    //     }
    //     return success('客户概念',$customerlist);
    // }

    /**
    *  @param userid  员工id
    *  @param external_userid 客户external_userid
    *  客户详情，客户动态  最近沟通时间暂时不做  自定义信息暂时不做
    *  添加好友，删除好友，客户删除，员工删除
    */
    public function dynamics(){
        $external_userid = $this->req->param("external_userid");
        $staff_id = $this->req->param("staff_id");
        if(!$external_userid) return error("参数错误");
        $dynamicsAll = CustomerModel::dynamicsAll($external_userid,$staff_id);

        return success('客户动态',$dynamicsAll);
    }

    public function setfieldList(){
        $wid = Session::get("wid");
        // $external_userid = $this->req->param("external_userid");
        // $staff_id = $this->req->param("staff_id");
        $id = $this->req->param("id");
        $setfield_list = CustomerModel::setfieldList($id);

        return success("获取成功",$setfield_list);
    }

    //修改自定义信息
    public function updUserFields(){
        $id = $this->req->param("id");
        $field_id = $this->req->param("field_id");
        $content = $this->req->param("content");
        $res = CustomerModel::updUserFields($id,$field_id,$content);

        return success("获取成功",$res);
    }

    public function setfield(){
        $wid = Session::get("wid");
        $res = CustomerModel::setfield($wid);

        return success("操作成功",$res);
    }

    public function upload(){
        $input_value = $this->req->param('input_value');
        $name = $this->req->param('name');
        $id = $this->req->param('id');
        $customer = Helper::getCustomer(["id"=>$id]);
        $wid = $customer["wid"];
        $times = $customer["createtime"];
        $config = Helper::getConfig($wid);
        $selfapp = Helper::getSelfapp($wid);
        $data[$name] = $input_value;
        $external_userid = $customer["external_userid"];
        $staff = Helper::getUser(["id"=>$customer["staff_id"]]);
        if($name == "remark_mobiles"){
            $mobile = explode(",",$input_value);
            foreach ($mobile as $key => $value) {
                if(strlen($value) != 11)return error("手机号格式错误");
            }
            $param = ['userid'=>$staff['userid'],'external_userid'=>$external_userid,'remark_mobiles'=>$mobile];
            $res = QyWechatApi::externalcontactRemark($param,$wid);
            $mobiles = json_encode(explode(",", $input_value),320);
            if($res["errmsg"] != "ok")return error("操作失败",$res["errcode"]);
            $data["remark_mobiles"] = $mobiles;
        }else if($name == "description"){
            if($customer["description"] == $input_value)return error("未修改");
            $param = ['userid'=>$staff['userid'],'external_userid'=>$external_userid,'description'=>$input_value];
            $res = QyWechatApi::externalcontactRemark($param,$wid);
            if($res["errmsg"] != "ok")return error("操作失败",$res["errcode"]);
            $data["description"] = $input_value;
        }
        Db::table("kt_wework_customer")->where(["id"=>$id])->save($data);

        return success('修改成功',$input_value);
    }

    /**
    *  @param userid  员工id
    *  @param external_userid 客户external_userid
    *  聊天记录需要会话存档，暂不做
    */
    public function dynamicss(){
        $external_userid = $this->req->param("external_userid");
        $userid = $this->req->param("userid");
        if(!$userid || !$external_userid) return error("参数错误");
        return success('聊天记录',array());
    }

    /**
    *  @param external_userid 客户 external_userid
    *  所在群聊
    */
    public function groupList(){
        $external_userid = $this->req->param("external_userid");
        $staff_id = $this->req->param("staff_id");
        if(!$external_userid) return error("参数错误");
        $groupList = CustomerModel::groupList($external_userid,$staff_id);
        return success('所在群聊',$groupList);
    }

    /*
    * 客户详情 所属员工
    */
    public function customerUser(){
        $addWay = addWay();
        $external_userid = $this->req->param("external_userid");
        if(!$external_userid) return error("参数错误");
        $customerlist = CustomerModel::customerUser($external_userid,$addWay);

        return success('所属员工',$customerlist);
    }
}